package io.mvvm.netty.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * @program: Netty
 * @description:
 * @author: 潘
 * @create: 2021-04-24 00:20
 **/
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private final static Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);

    /**
     * 当通道就绪时触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

//        for (int i = 0; i < 10; i++) {
//            ByteBuf buf = Unpooled.copiedBuffer("Hello Client" + i, CharsetUtil.UTF_8);
//            ctx.writeAndFlush(buf);
//        }

        ByteBuf buffer = ctx.alloc().buffer();
        char c = '0';
        Random r = new Random();
        for (int i = 0; i < 10; i++) {
            byte[] bytes = getBytes(c, r.nextInt(256) + 1);
            buffer.writeBytes(bytes);
            c++;
        }
        ctx.writeAndFlush(buffer);
    }

//    private static byte[] getBytes(char c, int i) {
//        StringBuilder sb = new StringBuilder();
//        for (int i1 = 0; i1 < i; i1++) {
//            sb.append(c);
//        }
//        int length = sb.length();
//        for (int i1 = 0; i1 < 10 - length; i1++) {
//            sb.append("-");
//        }
//        System.out.println(sb.toString());
//        return sb.toString().getBytes(StandardCharsets.UTF_8);
//    }

    private static byte[] getBytes(char c, int i) {
        StringBuilder sb = new StringBuilder();
        for (int i1 = 0; i1 < i; i1++) {
            sb.append(c);
        }
        sb.append("\n");
        System.out.println(sb.toString());
        return sb.toString().getBytes(StandardCharsets.UTF_8);
    }

    /**
     * 读取服务端发送的消息
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        logger.info("服务端回复的消息 : {}", buf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
